// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    //首先找到所有的openid
    var openid = new Array();
    var skip = 0;
    while (true) {
      var inquiry = await db.collection('user').skip(skip).get();
      var sizeTemp = inquiry.data.length;
      if (sizeTemp < 100) { //小于100表示所有的数据均已查到
        for (let i = 0; i < sizeTemp; i++) {
          openid.push(inquiry.data[i].openid);
        }
        break;
      } else if (sizeTemp == 100) { //等于100表示有可能还有未查到的数据
        for (let i = 0; i < sizeTemp; i++) {
          openid.push(inquiry.data[i].openid);
        }
        skip += 100;
      }
    }
    //openid 里面存着现在所有用户的id
    const size = openid.length;

    var timeStamp = new Date().getTime();

    for (let i = 0; i < size; i++) {
      var total = await db.collection('message').where({
        user_id: openid[i],
      }).count();

      await db.collection('message').add({
        data: {
          content: event.content,
          date: timeStamp,
          message_id: total.total,
          read: false,
          title: event.title,
          user_id: openid[i],
        }
      })
    }
    return {
      date: timeStamp,
      msg: 'ok',
    }
  } catch (e) {
    console.error(e);
  }

}